<?php
declare (strict_types=1);

namespace app\common\command;

use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\Output;

/**
 * php think task start
 */
class Task extends Command
{
    private $taskGroupList = [
        [
            'sendExceptionMessage',
            'orderBonusProcess',
            'orderBonusSettlementProcess',
            'userRanking',
            'executeSql',
            'aiImportQuestion',
            'buildOne23PanSession',
            'updateEsCourseSearchData',
            'indexEsCourseQuestionData',
        ],
        ['buildAiExplanation'],
        ['processUserAnswerQueue']
    ];

    protected function configure()
    {
        // 指令配置
        $this->setName('task')
            //增加一个命令参数
            ->addArgument('action', Argument::OPTIONAL, "action", '');
    }

    protected function execute(Input $input, Output $output)
    {
        // 输入参数
        $action = trim($input->getArgument('action'));

        // 配置任务
        $task = new \EasyTask\Task();
        $task->setDaemon(true);
        $task->setRunTimePath(app()->getRuntimePath());
        $taskGroupList = $this->taskGroupList;

        // 循环分组
        foreach ($taskGroupList as $index => $group) {
            $task->addFunc(function () use ($group) {
                foreach ($group as $item) {
                    $cmd = PHP_BINARY . ' think cron ' . $item;
                    shell_exec($cmd);
                }
            }, 'task' . $index);;
        }

        // 根据命令执行
        if ($action == 'start') {
            $task->start();
        } elseif ($action == 'status') {
            $task->status();
        } elseif ($action == 'stop') {
            $task->stop(true);
        } else {
            exit('Command is not exist');
        }
    }
}
